package com.dqhl.community.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.adapter.PhotoAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.view.LuocangDialog;
import com.dqhl.community.view.PictureSelectPopupWindow;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LIENLIN on 2016/9/9.
 * 社区医疗
 */
public class CommuunityHealth extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private TextView tvTopOpeartion;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private TextView tvIllName;
    private EditText mEtZhengZhuang;//症状
    private EditText mEtMiaoShu;//症状描述
//    private ImageView mIvPhoto;//拍照
    private LinearLayout mLinearLeft;//左时间轮播
    private LinearLayout mLinearRight;//左时间轮播
    private GridView mGvPhoto;//照片
    private SharedPreferences sp;
    private PictureSelectPopupWindow pictureSelectPopupWindow; // 照片选择popupwindow
    private static int REQUESTCODE_PICTURE = 100;
    private static int REQUESTCODE_CAMERA = 101;
    //时间选择器
    TimePickerDialog mStarDialogMonthDayHourMinute;
    TimePickerDialog mEndDialogMonthDayHourMinute;
    TimePickerDialog mDialogAll;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
    private String userid;
    private String picturePath;//相册照片路径
    private List<String>imgPathList=new ArrayList<>();
    private PhotoAdapter adapter;
    private long mill=0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_community_health);

        initView();
        TimePicker();
    }

    private void initView() {
        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopOpeartion = (TextView) findViewById(R.id.tv_top_commit);
        tvStartTime = (TextView) findViewById(R.id.tv_starttime);
        tvEndTime = (TextView) findViewById(R.id.tv_endtime);
        tvIllName = (TextView) findViewById(R.id.tv_illname);
        mEtZhengZhuang = (EditText) findViewById(R.id.et_zhengzhanug);
        mEtMiaoShu = (EditText) findViewById(R.id.et_miaoshu);

        mGvPhoto = (GridView) findViewById(R.id.gv_photo);
        mLinearLeft = (LinearLayout) findViewById(R.id.linear_time_left);
        mLinearRight = (LinearLayout) findViewById(R.id.linear_time_right);

        tvTopTitle.setText(R.string.tv_hospital);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopOpeartion.setVisibility(View.VISIBLE);
        tvTopOpeartion.setOnClickListener(this);
        ivTopBack.setOnClickListener(this);
        mLinearLeft.setOnClickListener(this);
        mLinearRight.setOnClickListener(this);
//        mIvPhoto.setOnClickListener(this);
        //获取userid
        sp= getSharedPreferences(Constant.USER_INFO, MODE_PRIVATE);
        userid = sp.getString(Constant.USERID, "");
        adapter = new PhotoAdapter(this, imgPathList);
        mGvPhoto.setAdapter(adapter);
        mGvPhoto.setOnItemClickListener(CommuunityHealth.this);
        //预约人姓名
        String name = spUserInfo.getString(Constant.NAME, "未知");
        tvIllName.setText(name);

        pictureSelectPopupWindow = new PictureSelectPopupWindow(this,pictureSelectItemsOnClick);
        pictureSelectPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pictureSelectPopupWindow.backgroundAlpha(1.0f);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == REQUESTCODE_PICTURE && resultCode == RESULT_OK) {
                Uri selectedImage = geturi(data);
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                if (c != null) {
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePathColumns[0]);
                    picturePath = c.getString(columnIndex);
                    Dlog.e("picturePath=========" + picturePath);
                    c.close();
                    imgPathList.add(picturePath);
                    adapter.notifyDataSetChanged();

                }

            }
            if (requestCode == REQUESTCODE_CAMERA && resultCode == RESULT_OK) {
                String sdState = Environment.getExternalStorageState();
                if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                    Dlog.e("sd card unmount");
                }
                String name = UUID.randomUUID().toString() + ".jpg";
                File file = new File("/sdcard/pintu");
                file.mkdirs();
                Bundle bundle = data.getExtras();
                //获取相机返回的数据，并转换为图片格式
                Bitmap bitmap = (Bitmap) bundle.get("data");
                FileOutputStream fout = null;
                String fileName = file.getPath() + name;
                try {
                    fout = new FileOutputStream(fileName);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fout.flush();
                        fout.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                imgPathList.add(fileName);
                adapter.notifyDataSetChanged();
            }
        }
    }

    View.OnClickListener pictureSelectItemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.btn_take_photo:   // 调用系统相机
                    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(camera, REQUESTCODE_CAMERA);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_pick_photo:   // 调取手机相册
                    Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(picture, REQUESTCODE_PICTURE);
                    pictureSelectPopupWindow.dismiss();
                    break;
                case R.id.btn_cancel:   // 取消
                    pictureSelectPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.tv_top_commit:
                //TODO
                String zhengzhuang = mEtZhengZhuang.getText().toString();
                String starttime = tvStartTime.getText().toString();
                String endtime = tvEndTime.getText().toString();
                String miaoshu = mEtMiaoShu.getText().toString();
                if (TextUtils.isEmpty(zhengzhuang)||TextUtils.isEmpty(starttime)||TextUtils.isEmpty(endtime)||TextUtils.isEmpty(miaoshu)){
                    final LuocangDialog dialog = new LuocangDialog(CommuunityHealth.this, "个人信息不完善", "请完善个人信息后才可以进行此操作", "确认");
                    dialog.setButtonClickListener(new LuocangDialog.ButtonClickListener() {
                        @Override
                        public void doConfirm() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }else {
                    commitHealthInfo(userid,zhengzhuang,starttime,endtime,miaoshu,imgPathList);
                }

                break;
            case R.id.linear_time_left:
                mStarDialogMonthDayHourMinute.show(getSupportFragmentManager(), "month_day_hour_minute");
                break;
            case R.id.linear_time_right:
                if (mill==0){
                    toast("请先选择开始日期");
                }else {
                    mEndDialogMonthDayHourMinute.show(getSupportFragmentManager(), "month_day_hour_minute");
                }
                break;
        }
    }
    /**
     * 显示发送内容来源
     */
    private void sendImg(){
            pictureSelectPopupWindow.showAtLocation(findViewById(R.id.lineat_health), Gravity.BOTTOM, 0, 0);
            pictureSelectPopupWindow.backgroundAlpha(0.5f);
    }
    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }
    //时间选择器
    public void TimePicker(){

        mStarDialogMonthDayHourMinute = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);
                        long nowTime = System.currentTimeMillis();
                        if (nowTime<millseconds){
                            mill = millseconds;
                            tvStartTime.setText(text);
                        }else {
                            toast("请大于当前日期");
                        }
                    }
                })
                .build();
        mEndDialogMonthDayHourMinute = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setCallBack(new OnDateSetListener() {
                    @Override
                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                        String text = getDateToString(millseconds);

                        if (mill<millseconds){
                            tvEndTime.setText(text);
                        }else {
                            toast("请大于开始日期");
                        }

                    }
                })
                .build();
    }

    /**
     * 提交预约
     * @param userid
     * @param zhengzhuang
     * @param starttime
     * @param endtime
     * @param miaoshu
     * @param imgpath
     */
    private void commitHealthInfo(String userid, String zhengzhuang, String starttime, String endtime, String miaoshu, List<String> imgpath){
        String[] str={"a","b","c","d","e","f","g","h","i"};
        Dlog.e("onSuccess==" + userid+"/"+ zhengzhuang+"/"+ starttime+"/"+ endtime+"/"+ miaoshu+"/");

        RequestParams params = new RequestParams(Config.Api.commit_health);
        params.addBodyParameter("user_id", userid);
        params.addBodyParameter("illness_type", zhengzhuang);
        params.addBodyParameter("illness_info", miaoshu);
        params.addBodyParameter("start_time", starttime);
        params.addBodyParameter("end_time", endtime);
        if (imgpath.size()>0){
            for (int i=0;i<imgpath.size();i++){
                Dlog.e("commitHealthInfo==" + imgpath.get(i));
                File imgfile=new File(imgpath.get(i));
                params.addBodyParameter("pic_"+str[i], imgfile);
            }
        }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("commitHealthInfo==" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 0) {
                    String errMsg = JsonUtils.getInfo(result, "data");
                    final LuocangDialog dialog = new LuocangDialog(CommuunityHealth.this, errMsg, "医生很快就会与您联系\n请保持手机畅通", "确认");
                    dialog.setButtonClickListener(new LuocangDialog.ButtonClickListener() {
                        @Override
                        public void doConfirm() {
                            dialog.dismiss();
                            overlay(CommunityHealthRecordActivity.class);
                            CommuunityHealth.this.finish();
                        }
                    });
                    dialog.show();

                } else {
                    toast("预约失败");
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Dlog.e("commitHealthInfo==" + ex.toString());
                toast(R.string.error_net_connection);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
                Dlog.e("commitHealthInfo"+"onFinished()");
            }
        });

    }

    /**
     * 解决小米部分手机调用系统相册失败
     * @param intent
     * @return
     */
    public Uri geturi(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        if (i==0){
            sendImg();
        }else {
            String path = (String) adapterView.getItemAtPosition(i);
            boolean remove = imgPathList.remove(path);
            adapter.notifyDataSetChanged();
            Log.d("CommunityHealth","删除" + imgPathList.size());
        }
    }
}
